#define __FORCE_TRACE__
//#define __FORCE_DEBUG__
//#define __FORCE_INFO__
#define THIS_FILE "client\fn_serverExecuteReleaseAI.sqf"
#include <tmf_constants.h>
#include <tmf_macros.h>

TRACE_1("Start",_this);
TMFPROFILERSTART;

private ["_caller","_target","_group","_object","_player","_actions","_released","_groups","_grp_ai","_action_id","_i","_initial_side","_wp"];
DEFAULT_PARAM(_target,0,east);
DEFAULT_PARAM(_caller,0,east);

_group = group _target;
_released = [];
_groups = [] call FFUNC(hashEmpty);

{
	if (!isplayer _x) then {
		_object = _x;
		_actions = [_object,"LEAD"] call FFUNC(getActions);
		TRACE_1("Actions",_actions);
		if (count _actions > 0) then {
			_action_id = [(_actions select 0)] call FFUNC(actionGetID);
			_grp_ai = [_groups, _action_id,grpNull,THIS_FILE] call FFUNC(hashGet);
			TRACE_1("Grp AI",_grp_ai);
			if (isNull _grp_ai) then {
				_initial_side = OGETVAR(_object,QGVAR(INITIAL_SIDE),GVAR(own_side));
				_grp_ai = [_initial_side] call FFUNC(createGroup);
				_grp_ai allowFleeing 0;
				_groups = [_groups, _action_id,_grp_ai] call FFUNC(hashSet);
				[_object] joinSilent _grp_ai;
				TRACE_2("Grp Added",_grp_ai, units _grp_ai);
				[_grp_ai] call FFUNC(deleteWaypoints);
				_wp = _grp_ai addWaypoint [getPos _object, 0];
				_wp setWaypointType "HOLD";
				_wp = _grp_ai addWaypoint [getPos _object, 0];
				_wp setWaypointType "CYCLE";
				_grp_ai setCurrentWaypoint _wp;
			} else {
				[_object] joinSilent _grp_ai;
			};
			TRACE_2("Joined AI to Group",_object,_grp_ai);
			_released set[count _released, _object];
			(leader _grp_ai) doMove (waypointPosition [_grp_ai,(currentWaypoint _grp_ai)]);
		} else {
			TRACE_1("AI has no actions",ARR_2(_object,typeof _object));
		};
	};
} foreach units _group;
TRACE_1("Groups",_groups);
// The following code is meant to delete empty groups, it should be done at a higher level.
// [_groups] spawn {
	// TRACE_1("Watcher",_this);
	// private ["_groups","_i","_leader","_grp","_actions","_grps"];
	// DEFAULT_PARAM(_groups,0,[]);
	// _actions = _groups select 0;
	// _grps = _groups select 1;
	// while {(count _actions > 0)} do {
		// sleep 20.345678;
		// for [{_i = 0},{_i < (count _actions)},{_i = _i + 1}] do {
			// _grp = (_grps select _i);
			// _leader = leader _grp;
			// if (alive _leader) then {
				// _leader doMove (waypointPosition [_grp,1]);
			// } else {
				// if (({alive _x} count (units _grp)) <= 0) then {
					// deletegroup _grp;
				// };
				// _grps set [_i, "XxDeLxX"];
				// _actions set [_i, "XxDeLxX"];
			// };
		// };
		// _grps = _grps - ["XxDeLxX"];
		// _actions = _actions - ["XxDeLxX"];
	// };
// };
TRACE("End");
TMFPROFILERSTOP;